package io.virtualapp.abs.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.flurry.android.FlurryAgent;
import com.githang.statusbar.StatusBarCompat;

import org.greenrobot.eventbus.EventBus;
import org.jdeferred.android.AndroidDeferredManager;
import org.litepal.LitePal;
import org.litepal.crud.DataSupport;

import java.util.Map;

import io.virtualapp.R;
import io.virtualapp.VApp;
import io.virtualapp.abs.BaseView;
import io.virtualapp.bean.ApliyBean;
import io.virtualapp.bean.EventBusMakeBean;
import io.virtualapp.bean.PayResult;
import io.virtualapp.bean.UpdateBean;
import io.virtualapp.bean.Vip;
import io.virtualapp.mylibrary.callback.BaseCallback;
import io.virtualapp.mylibrary.http.HttpUtils;
import io.virtualapp.mylibrary.util.ToastUtils;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author Lody
 */
public class VActivity extends AppCompatActivity {
    public static Vip vip;
    protected Context mContext;
    protected Activity mActivity;
    /**
     * Implement of {@link BaseView#getActivity()}
     */
    public Activity getActivity() {
        return this;
    }

    /**
     * Implement of {@link BaseView#getContext()} ()}
     */
    public Context getContext() {
        return this;
    }

    protected AndroidDeferredManager defer() {
        return VUiKit.defer();
    }

    public Fragment findFragmentById(@IdRes int id) {
        return getSupportFragmentManager().findFragmentById(id);
    }

    public void replaceFragment(@IdRes int id, Fragment fragment) {
        getSupportFragmentManager().beginTransaction().replace(id, fragment).commit();
    }

    @Override
    protected void onStart() {
        super.onStart();
        FlurryAgent.onStartSession(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        FlurryAgent.onEndSession(this);
    }
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        mActivity = this;
        // 获取vip状态
        StatusBarCompat.setStatusBarColor(VActivity.this,
                getResources().getColor(R.color.white),
                true);
        if (DataSupport.findFirst(Vip.class) != null) {
            vip = DataSupport.findFirst(Vip.class);
        }
        VApp.addActivity(this);
    }
    public void openActionView(String url){
        if (!TextUtils.isEmpty( url )){
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setData( Uri.parse(url));
            startActivity(intent);
        }
    }
    private static final int SDK_PAY_FLAG = 1;
    protected PaysuccessListener PayListener;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what){
                case SDK_PAY_FLAG:
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    switch (payResult.getResultStatus()){
                        case "9000":
                            updataVip();
                             if (PayListener!=null){
                                PayListener.PaySuccess();
                            }
                            break;
                        case "8000":
                            ToastUtils.showShortToast("正在处理中");
                            if (PayListener!=null){
                                PayListener.PayFail(payResult.getResultStatus());
                            }
                            break;
                        case "4000":
                            ToastUtils.showShortToast("订单支付失败");
                            if (PayListener!=null){
                                PayListener.PayFail(payResult.getResultStatus());
                            }
                            break;
                        case "5000":
                            ToastUtils.showShortToast("重复请求");
                            if (PayListener!=null){
                                PayListener.PayFail(payResult.getResultStatus());
                            }
                            break;
                        case "6001":
                            ToastUtils.showShortToast("已取消支付");
                            if (PayListener!=null){
                                PayListener.PayFail(payResult.getResultStatus());
                            }
                            break;
                        case "6002":
                            ToastUtils.showShortToast("网络连接出错");
                            if (PayListener!=null){
                                PayListener.PayFail(payResult.getResultStatus());
                            }
                            break;
                        case "6004":
                            ToastUtils.showShortToast("正在处理中");
                            if (PayListener!=null){
                                PayListener.PayFail(payResult.getResultStatus());
                            }
                            break;
                        default:
                            ToastUtils.showShortToast("支付失败");
                            if (PayListener!=null){
                                PayListener.PayFail(payResult.getResultStatus());
                            }
                            break;
                    }
                    //有支付意愿的，取消他的不再提醒
                    break;
            }

        }
    };
    /**
     *      支付宝购买
     * @param pid
     */
    protected void pay(int pid){
        HttpUtils.getInstance().postOrder(1,pid,0,2,new BaseCallback<ApliyBean>(){
            @Override
            public void onRequestBefore() {

            }

            @Override
            public void onFailure(Request request, Exception e) {
                ToastUtils.showShortToast("链接超时");
            }

            @Override
            public void onSuccess(Response response, ApliyBean apliyBean) {
                if (response.isSuccessful()){
                    if (apliyBean != null){
                        if (!apliyBean.isIssucc()){
                            ToastUtils.showShortToast(apliyBean.getMsg());
                            return;
                        }
                        Runnable runnable = ()->{
                            PayTask alipay = new PayTask(mActivity);
                            Map<String, String> map = alipay.payV2(apliyBean.getPackage_str(),true);
                            Message msg = new Message();
                            msg.what = SDK_PAY_FLAG;
                            msg.obj = map;
                            mHandler.sendMessage(msg);
                        };

                        Thread payThread = new Thread(runnable);
                        payThread.start();

                    }
                }
            }
            @Override
            public void onError(Response response, int errorCode, Exception e) {

            }
        });
    }
    protected void updataVip(){
        HttpUtils.getInstance().postUpdate(new BaseCallback<UpdateBean>() {
            @Override
            public void onRequestBefore() {

            }

            @Override
            public void onFailure(Request request, Exception e) {

            }

            @Override
            public void onSuccess(Response response, UpdateBean o) {
                if (o!=null&&response.isSuccessful()){
                    vip = o.getVip();
                    if (DataSupport.findFirst(Vip.class) != null){
                        DataSupport.deleteAll(Vip.class);
                    }
                    vip.save();
                }
            }
            @Override
            public void onError(Response response, int errorCode, Exception e) {

            }
        });
    }
    public void setPayListener(PaysuccessListener payListener) {
        PayListener = payListener;
    }

    public interface PaysuccessListener{
        public void PaySuccess();
        public void PayFail(String resultstatu);
    }

}
